class Solution {
    // public boolean validateStackSequences(int[] pushed, int[] popped) {
    //     // 让元素一致进栈，并判断是否需要出栈即可
    //     Stack<Integer> stack = new Stack<>();
    //     int i = 0, j = 0, m = pushed.length, n = popped.length;
    //     while (i < n) {
    //         stack.push(pushed[i]);
    //         while (!stack.isEmpty() && stack.peek() == popped[j]) {
    //             stack.pop();
    //             j++;
    //         }
    //         i++;
    //     }
    //     return stack.isEmpty();
    // }


    // 下面的代码只能判断0-9之间的数字，对于两位数就无法判断了
    public static boolean validateStackSequences(int[] pushed, int[] popped) {
        // 让元素一致进栈，并判断是否需要出栈即可
        StringBuilder builder = new StringBuilder();
        int i = 0, j = 0, m = pushed.length, n = popped.length;
        while (i < n) {
            builder.append(pushed[i]);
            while (builder.length() != 0 && builder.charAt(builder.length()-1) - '0' == popped[j]) {
                builder.deleteCharAt(builder.length()-1);
                j++;
            }
            i++;
        }
        return builder.length() == 0;
    }

    public static void main(String[] args) {
        System.out.println(validateStackSequences(new int[]{1, 2, 3, 4, 5}, new int[]{4, 5, 3, 2, 1}));
    }
}